package cn.zt.service.impl;

import cn.zt.domain.dao.Airline;
import cn.zt.domain.dao.Type;
import cn.zt.mapper.ManageMapper;
import cn.zt.mapper.SelectMapper;
import cn.zt.mapper.TypeMapper;
import cn.zt.service.IManageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ManageServiceImpl extends ServiceImpl<ManageMapper, Airline> implements IManageService {

    @Resource
    private TypeMapper typeMapper;
    @Resource
    private SelectMapper selectMapper;

    @Override
    public String importFlightinfo(List<Airline> list, boolean updateSupport) {
        int successCount = 0;
        int failureCount = 0;
        if (list.isEmpty()){
            return "数据为空";
        }else  {
            System.out.println("开始导入");
            for (int i = 1; i <= list.size(); i++) {
                Airline airline = list.get(i - 1);
                try {
                    int insert = selectMapper.insert(airline);
                    if (insert == 0) {
                        failureCount++;
                        System.out.println("第" + i + "条数据导入失败");
                        continue;
                    }

                    Type type = new Type();
                    type.setFlightId(airline.getId());
                    type.setOneCount(airline.getCapacity() / 6);
                    type.setTwoCount(airline.getCapacity() * 2 / 6);
                    type.setThreeCount(airline.getCapacity() * 3 / 6);

                    // 不手动设置 id，让数据库自动生成
                    typeMapper.insert(type);
                    successCount++;
                } catch (DuplicateKeyException e) {
                    // 处理重复键异常，可以选择跳过或更新
                    System.out.println("类型记录已存在，跳过插入：" + airline.getId());
                    failureCount++;
                } catch (Exception e) {
                    // 捕获其他异常并记录
                    System.out.println("第" + i + "条数据导入时发生未知错误：" + e.getMessage());
                    failureCount++;
                }
            }
        }
        return "成功导入" + successCount + "条信息，失败" + failureCount + "条信息";
    }
}
